#include "showdata.h"
#include "ui_showdata.h"
#include "mysqlqt.h"
#include "sensordata.h"
#include "datatran.h"
#include "sensor.h"
#include  "datatran.h"
#include <QRandomGenerator>
#include <qmqtt.h>
#include "mqttfx.h"

ShowData::ShowData(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ShowData)
{
    ui->setupUi(this);
}

ShowData::~ShowData()
{
    delete ui;
}

// 连接传感器
void ShowData::on_ConnBut_clicked()
{
    Sensor* s = new Sensor();
    QString Id = ui->ConnectIdLine->text().trimmed();
    MySqlQt sql = MySqlQt();
    QSqlDatabase db = sql.db;
    sql.ConnectSql(db);
    sen = sql.SelectEquiById(db,Id);
    signal_str = sen->Signal;
    if(signal_str == "数字量")
    {
        qDebug() << "GenDigDa";
        QByteArray array;
        array = s->GenDigData();
        qDebug() << array.toHex();
        ui->DaraTextEdit->setText(array.toHex().toUpper());
    }
    if(signal_str == "模拟量")
    {
        float value = s->GenAnalogData();
        ui->DaraTextEdit->setText(QString::number(value,'f',10));

    }
}

void ShowData::on_OrignDataBut_clicked()
{
    if(signal_str == "模拟量")
    {
        QString value_str = ui->DaraTextEdit->toPlainText();
        ui->DaraTextEdit->setText(value_str);
        return;
    }
    bool flag;
    QString value_str = ui->DaraTextEdit->toPlainText().trimmed();
    QByteArray array;
    for(int i = 0; i< value_str.size(); i+=2)
    {
        array.append(char(value_str.mid(i,2).toInt(&flag,16)));
    }
    float Value;
    memcpy(&Value,array.data(),array.size());
    ui->DaraTextEdit->setText(QString::number(Value,'f',2));
    ui->OrignDataBut->setEnabled(false);
}


void ShowData::on_CodeBtn_clicked()
{

}


void ShowData::on_DecodeBtn_clicked()
{

}

void ShowData::on_pushButton_clicked()
{
    MqttFx* mqttfx = new MqttFx();
    QMQTT::Client* client = mqttfx->InitClient();
    client->connectToHost();
    QString data = ui->SenEdit->toPlainText();
    mqttfx->SenOneNet(client,data);
}

